###############################################################################
#Programmers: Danil Dotsenko, dd@accentsolution.com                           #
#                                                                             #
#                                                                             #
#    Copyleft 2006 Danil Dotsenko                                             #
#                                                                             #
#    This program is free software; you can redistribute it and/or modify     #
#    it under the terms of the GNU General Public License as published by     #
#    the Free Software Foundation; either version 2 of the License, or        #
#    (at your option) any later version.                                      #
#                                                                             #
#    This program is distributed in the hope that it will be useful,          #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of           #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            #
#    GNU General Public License for more details.                             #
#                                                                             #
#    You should have received a copy of the GNU General Public License        #
#    along with this program; if not, write to the Free Software              #
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA #
#                                                                             #
###############################################################################

import os.path

print "loaded File plugin"

class pluginClass:
	'''
	Just random notes to myself. Real, helpfull comments will come later.
	'''
	def __init__(self):
		self.filterStr = '^file://'
		self.filterObj = None # this will be re.compile object, populated by main afoto code based on the filter above.
		self.protocol = 'file'
		print "Loading File plugin variables."
	
	def translatePath(self, path):
		'''
		This function would convert a usual url into internally stored url
		example: http://flickr.com/name/album/ would turn into flickr://id:APInum@blah/blah
		Some URLs, like "file://" are returned in the same way back
		'''
		return path
	
	def tryNextImage(self, widget, instance, common, customPath = None):
		'''
		This function prepares the image for consumption by setting a valid source to instance.cfg['currentPath']
		and changing instance.cfg['resourcePath'] in case when completely new source was dropped / chosen
		widget = widget mumber.
		common = pointer to appConfig.common a dictionary type with afoto-wide settings.
		instance = pointer to appConfig.instance[widget] a dictionary type with instance-specific settings.
		  instance.cfg['resourcePath'] already contains a proven, used source. 
		  if customPath is not usable or is not given, we will need to pull a new item out of instance.cfg['resourcePath']
		customPath = string (or unicode type) with new path we need to test.
		  We test if that path is workable and try to pull a picture, If OK, we make it a new resourcePath
		'''
		
		# FOR PLUGIN WRITERS:
		# there are 3 things that have to happen in this function:
		# 0. if customPath is given, we translate the normal URL into our internal URL. (usually done in parent function. not here)
		# 1. test the path (new from customPath or old from instance.cfg['resourcePath'])
		# 2. if path is ok, pull up a picture to the local drive and set the address to the file to instance.cfg['currentPath']
		# 3. if we used customPath for the source, set instance.cfg['resourcePath'] to the new address
		
		# Part 1 testing the path.
		
		if customPath:
			# it was dropped in or passed through URLOpen dialog and may be in raw format.
			testPath = self.translatePath(customPath)
		else:
			testPath = instance.cfg['resourcePath']
		
		success = False # Nothing is changed.
		
		# in File protocol, we only work with local paths, so, lets strip the protocol part.
		newpath = testPath[7:]
		
		# This may be a file or folder.
		# if FOLDER, we need to find a next image.
		if os.path.isdir(newpath):
			lista = []
			hitFileLimit = False
			for root, dirs, files in os.walk(newpath):
				if hitFileLimit:
					notificationWindow(_("The folder you chose contains more than %s images.\nReading this folder at each refresh may be very painful for the system. Please reorganize your sources.") % str(common['fileLimit']),_("Error"))
					break
				for name in files:
					if common['fileFilter'].search(name):
						lista.append(os.path.join(root, name))
					if lista.__len__() > common['fileLimit']:
						hitFileLimit = True
						break
			# parts 2 and 3 - setting new instance.cfg['resourcePath'] and new instance.cfg['currentPath']
			if lista.__len__() > 0:
				if customPath:
					instance.cfg['resourcePath'] = customPath
				instance.cfg['currentPath'] = lista[random.randint(0,lista.__len__()-1)]
				instance.unpause(widget)
				success = True
		# if single file we just need to test for its availability
		elif os.path.isfile(newpath):
			if common['fileFilter'].search(newpath):
				# parts 2 and 3 - setting new instance.cfg['resourcePath'] and new instance.cfg['currentPath']
				if customPath:
					instance.cfg['resourcePath'] = customPath
				instance.cfg['currentPath'] = newpath # !!! very important !!! see warning above. It can only be a local path without "file://"
				instance.pause(widget)
				success = True
		return success
